package com.hmall.trade.listener;

import cn.hutool.core.util.ObjUtil;
import com.hmall.api.client.PayClient;
import com.hmall.api.constants.OrderStatusConstants;
import com.hmall.api.constants.PayOrderStatusConstants;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.trade.constants.MQConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * 订单延迟消息监听器
 */
@Component
@RequiredArgsConstructor
public class OrderDelayMessageListener {

    private  final IOrderService orderService;

    private final PayClient payClient;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = MQConstants.DELAY_ORDER_QUEUE_NAME),
                    exchange = @Exchange(name = MQConstants.DELAY_EXCHANGE_NAME,delayed = "true"),
                    key = MQConstants.DELAY_ORDER_KEY
            )
    )
    public void listenOrderDelayMessage(Long orderId) {
        // 1. 查询订单
        Order order = orderService.getById(orderId);
        // 2. 判断订单状态，判断是否是已支付
        if(ObjUtil.isEmpty(order)|| order.getStatus() != OrderStatusConstants.UNPAID){
            // 订单不存在或者订单状态不是未支付，直接返回
            return;
        }

        // 3. 如果是未支付 ，需要查询订单流水
        PayOrderDTO payOrderDTO = payClient.queryPayOrderByBizOrderNo(orderId);

        // 4. 判断订单流水状态
        if(ObjUtil.isNotEmpty(payOrderDTO) && payOrderDTO.getStatus() == PayOrderStatusConstants.PAY_ORDER_STATUS_PAY_SUCCESS){
            // 4.1 如果是已支付，标记订单为已支付
            orderService.markOrderPaySuccess(payOrderDTO.getId());
        }else {
            // 4.2 如果是未支付，标记订单为已关闭 恢复库存
            orderService.cancelOrder(orderId);
        }


    }
}
